package com.jxsr.aspect;

import com.jxsr.annotation.IpControl;
import com.jxsr.annotation.Limitation;
import com.jxsr.exception.LimitationException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @Description :
 * @Author : Bruce Lee
 * @CreateTime : 2024/12/19
 */


@Slf4j
@Aspect
@Component
public class IpAspect {

    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 处理多个代理服务器的情况
            return ip.split(",")[0].trim();
        }
        // 客户端直连，不能有中间代理服务器
        return request.getRemoteAddr();
    }

    @Before(value = "@annotation(com.jxsr.annotation.IpControl)")
    public void before(JoinPoint joinPoint) {

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        String clientIp = getClientIp(request);

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        IpControl ipControl = methodSignature.getMethod().getAnnotation(IpControl.class);
        String[] split = ipControl.IpList().split(",");

        if (!Arrays.asList(split).contains(clientIp)){
            throw new LimitationException("无权访问");
        }


    }


}
